from datetime import timedelta
from typing import Any
from fastapi import APIRouter, Depends, HTTPException, status, Response
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session

from app.api import deps
from app.core import security
from app.schemas import auth
from app.database.models.base import User
from app.schemas.token import Token
from app.utils import logger

router = APIRouter()

@router.post("/login")
async def login(
    response: Response,
    db: Session = Depends(deps.get_db),
    form_data: OAuth2PasswordRequestForm = Depends()
):
    """
    用户登录
    """
    try:
        # 打印调试信息
        print(f"Attempting login for user: {form_data.username}")
        
        user = db.query(User).filter(User.username == form_data.username).first()
        if not user:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="用户名或密码错误"
            )
            
        # 打印调试信息
        print(f"Found user: {user.username}, role: {user.role}, active: {user.is_active}")
        
        if not security.verify_password(form_data.password, user.hashed_password):
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="用户名或密码错误"
            )
            
        if not user.is_active:
            raise HTTPException(
                status_code=status.HTTP_401_UNAUTHORIZED,
                detail="用户已被禁用"
            )
        
        # 允许 admin 和 agent 角色登录
        if user.role not in ["admin", "agent"]:
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="没有访问权限"
            )

        access_token = security.create_access_token(user.id)
        
        # 设置 cookie
        response.set_cookie(
            key="access_token",
            value=f"Bearer {access_token}",
            httponly=True,
            secure=True,  # 如果使用 HTTPS
            samesite='lax',
            domain='.hkpublicholiday.com'  # 注意这里的域名设置
        )
        
        return {
            "access_token": access_token,
            "token_type": "bearer"
        }
        
    except HTTPException as he:
        raise he
    except Exception as e:
        print(f"Login error: {str(e)}")  # 打印错误信息
        raise HTTPException(
            status_code=500,
            detail=f"登录时发生错误: {str(e)}"
        )

@router.post("/register", response_model=auth.User)
def register(
    *,
    db: Session = Depends(deps.get_db),
    user_in: auth.UserCreate,
) -> Any:
    """用户注册"""
    # 检查用户名是否已存在
    user = db.query(User).filter(User.username == user_in.username).first()
    if user:
        raise HTTPException(
            status_code=400,
            detail="Username already registered"
        )
    
    # 检查邮箱是否已存在
    user = db.query(User).filter(User.email == user_in.email).first()
    if user:
        raise HTTPException(
            status_code=400,
            detail="Email already registered"
        )
    
    # 创建新用户
    user = User(
        email=user_in.email,
        username=user_in.username,
        hashed_password=security.get_password_hash(user_in.password),
        workarea_id=user_in.workarea_id,
        role="staff",  # 默认角色
        is_active=True
    )
    db.add(user)
    db.commit()
    db.refresh(user)
    return user

@router.get("/me", response_model=auth.User)
async def read_users_me(current_user: User = Depends(deps.get_current_active_user)):
    logger.info(f"Accessing /me endpoint with user: {current_user}")
    print(f"Current user: {current_user.username}")
    # 手动构建返回字典
    return {
        "id": current_user.id,
        "email": current_user.email,
        "username": current_user.username,
        "is_active": current_user.is_active,
        "role": current_user.role,
        "workarea_id": current_user.workarea_id
    } 